using Godot;
using System;

public partial class TileMapLayer : Godot.TileMapLayer
{
    public AStarGrid2D AStarGrid = new AStarGrid2D();//用于路径查找的A*网格
    // Called when the node enters the scene tree for the first time.

    public override void _Ready()
    {
        AStarGrid.Region = GetUsedRect();//设置A*网格的区域为图块地图的已使用区域
        AStarGrid.CellSize = TileSet.TileSize;//设置A*网格的单
        AStarGrid.DefaultComputeHeuristic = AStarGrid2D.Heuristic.Manhattan;//设置启发式函数为曼哈顿距离
        AStarGrid.DefaultEstimateHeuristic = AStarGrid2D.Heuristic.Manhattan;
        AStarGrid.DiagonalMode = AStarGrid2D.DiagonalModeEnum.Never;//不允许对角移动
        AStarGrid.Update();
        GD.Print(AStarGrid.Region);
        // 获取图块大小
        Vector2I tileSize = TileSet.TileSize;
        GD.Print("单个图块大小: ", tileSize);

        // 获取图层像素大小
        Vector2 layerSize = GetLayerPixelSize();
        GD.Print("整个图层像素大小: ", layerSize);
    }

    public Vector2 GetLayerPixelSize()//通过计算已使用的图块位置来确定图层的像素大小（矩形）
    {
        var usedCells = GetUsedCells();//获得已使用的图块位置列表

        if (usedCells.Count == 0)
            return Vector2.Zero;

        var minPos = usedCells[0];
        var maxPos = usedCells[0];

        foreach (Vector2I cell in usedCells) // 遍历所有已使用的图块位置，找到最小和最大坐标
        {
            minPos.X = Mathf.Min(minPos.X, cell.X);
            minPos.Y = Mathf.Min(minPos.Y, cell.Y);
            maxPos.X = Mathf.Max(maxPos.X, cell.X);
            maxPos.Y = Mathf.Max(maxPos.Y, cell.Y);
        }

        Vector2I tileSize = TileSet.TileSize;//获取图块大小
        float widthPixels = (maxPos.X - minPos.X + 1) * tileSize.X;//计算宽度
        float heightPixels = (maxPos.Y - minPos.Y + 1) * tileSize.Y;//计算高度

        return new Vector2(widthPixels, heightPixels);
    }

    public Vector2 GetTilePixelPosition(Vector2I tileCoords)//通过图块坐标获取图块的像素位置
    {
        return MapToLocal(tileCoords);
    }

    public Rect2 GetTilePixelRect(Vector2I tileCoords)//通过图块坐标获取图块的像素矩形区域
    {
        Vector2I tileSize = TileSet.TileSize;
        Vector2 pixelPos = MapToLocal(tileCoords);

        return new Rect2(pixelPos, tileSize);
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
	{
	}
}
